import { useState } from "react"
import { message } from "antd"
import { getDeptList, deleteDept, updateDept, addDept } from "api/system/dept"
import { convertTreeSelectData } from "utils/adaptation"

import { IModalProps } from "app/interfaces/system"

interface IForm {
  deptId: string
  parentId: string
  ancestors: string
  deptName: string
  orderNum: number
  leader: string
  phoneNumber: string
  email: string
  status: string
  delFlag: string
}

export interface IEditProps extends IModalProps<IForm> {
  treeData: never[]
  submitForm: (params: IForm) => void
}

export function useDept() {
  const initForm = {
    deptId: "",
    parentId: "",
    ancestors: "",
    deptName: "",
    orderNum: 0,
    leader: "",
    phoneNumber: "",
    email: "",
    status: "1",
    delFlag: ""
  }

  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([])
  const [queryParams, setQueryParams] = useState({ deptName: "", status: "" })

  const [form, setForm] = useState<IForm>(initForm)
  const [modalConfig, setModalConfig] = useState({
    title: "",
    visible: false
  })

  const getList = async () => {
    try {
      setLoading(true)
      const { code, data } = await getDeptList(queryParams)
      if (code === 200) {
        setDataSource(convertTreeSelectData(data, ["deptId", "deptName"]))
      }
      setLoading(false)
    } catch (e) {
      console.log(e)
      setLoading(false)
    }
  }

  const submitForm = async (params) => {
    const service = params.deptId ? updateDept : addDept
    const { code } = await service(params)
    if (code === 200) {
      setModalConfig({ ...modalConfig, visible: false })
      message.success("操作成功")
      await getList()
    }
  }

  const handleDelete = async (deptId) => {
    try {
      const { code } = await deleteDept(deptId)
      if (code === 200) {
        message.success("删除成功")
        await getList()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    getList,
    handleDelete,
    submitForm,
    loading,
    setLoading,
    dataSource,
    setDataSource,
    queryParams,
    setQueryParams,
    initForm,
    form,
    setForm,
    modalConfig,
    setModalConfig
  }
}
